package com.sugon.api;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.sugon.annotation.AuthCheck;
import com.sugon.annotation.LoginUser;
import com.sugon.entity.*;
import com.sugon.entity.dto.TreeNode;
import com.sugon.modules.mold.service.IMoldArchivesManager;
import com.sugon.modules.mold.service.IMoldRepairRecordManager;
import com.sugon.modules.mold.service.IMoldReplacePartManager;
import com.sugon.modules.sys.model.vo.PickerModel;
import com.sugon.service.ModulPositionCorrelationService;
import com.sugon.service.ModuleArchivesService;
import com.sugon.service.ModuleTypeService;
import com.sugon.service.SysConfigService;
import com.sugon.util.ApiBaseAction;
import com.sugon.utils.PageUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 模具业务API
 *
 * @author YuXD
 * @since 2022-05-27
 */
@Api(tags = "模具业务API")
@RestController
public class MoldBaseApiController extends ApiBaseAction {

    @Autowired
    private ModuleArchivesService moduleArchivesService;
    @Autowired
    private IMoldArchivesManager moldArchivesManager;
    @Autowired
    private IMoldReplacePartManager moldReplacePartManager;
    @Autowired
    private IMoldRepairRecordManager moldRepairRecordManager;
    @Autowired
    private ModuleTypeService moldTypeService;
    @Resource
    private ModulPositionCorrelationService modulPositionCorrelationService;
    @Resource
    private SysConfigService configService;

    /**
     * 模具查询API
     *
     * @param loginUser 当前登录用户
     * @param params    查询参数
     * @return
     */
    @AuthCheck
    @ApiOperation(value = "模具查询API")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "moduleNo", value = "模具号", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "moduleCode", value = "模具编码", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "productMode", value = "模具机型", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "moduleSeries", value = "模具系列", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "moduleType", value = "模具类别", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "currentState", value = "模具状态", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "liveCode", value = "现场使用码", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "dept", value = "所属车间", paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "page", value = "当前页码", paramType = "query", dataType = "int", required = true),
            @ApiImplicitParam(name = "limit", value = "每页记录数", paramType = "query", dataType = "int", required = true)
    })
    @PostMapping(value = {"/api/vi/molds"})
    public ApiResult<PageUtils> getModList(@ApiIgnore @LoginUser SysUserEntity loginUser, @ApiIgnore @RequestParam Map<String, Object> params) {
        ApiResult<PageUtils> apiResult = new ApiResult<>();
        return apiResult.success(moldArchivesManager.queryList(params));
    }

    /**
     * 模具查询API
     *
     * @param loginUser 当前登录用户
     * @param params
     * @return
     */
    @AuthCheck
    @ApiOperation(value = "模具查询API，PAD用")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "moldCode", value = "模具号", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "page", value = "当前页码", paramType = "query", dataType = "int", required = true),
            @ApiImplicitParam(name = "limit", value = "每页记录数", paramType = "query", dataType = "int", required = true)
    })
    @PostMapping(value = {"/api/vi/mold/list"})
    public ApiResult<PageUtils> getModListForPad(@ApiIgnore @LoginUser SysUserEntity loginUser, @ApiIgnore @RequestParam Map<String, Object> params) {
        ApiResult<PageUtils> apiResult = new ApiResult<>();
        String moldCode = MapUtil.getStr(params, "moldCode");
        if (StrUtil.isNotEmpty(moldCode)) {
            params.put("moduleNo", moldCode);
            params.remove("moldCode");
        }
        return apiResult.success(moldArchivesManager.queryList(params));
    }

    @ApiOperation(value = "根据模具号查询API")
    @ApiImplicitParam(name = "moduleNo", value = "模具号", required = true, dataType = "string", paramType = "query")
    @RequestMapping("/api/vi/mold/getByMoldNo")
    public ApiResult<List<PickerModel>> getByMoldNo(@RequestParam String moduleNo) {
        ApiResult<List<PickerModel>> apiResult = new ApiResult<>();
        // 至少输入四个字符进行查询
        if (StrUtil.isEmpty(moduleNo) || moduleNo.length() < 4) {
            return apiResult.failMsg("请至少输入四个字符进行查询！");
        }
        List<PickerModel> moldList = CollectionUtil.newArrayList();
        Map<String, Object> param = MapUtil.newHashMap();
        param.put("moduleNo", moduleNo);
        List<ModuleArchivesEntity> matchedMoldList = moduleArchivesService.queryList(param);
        // 整合数据到一起
        for (ModuleArchivesEntity mold : matchedMoldList) {
            moldList.add(new PickerModel(mold.getModuleNo(), mold.getId()));
        }
        return apiResult.success(moldList);
    }

    /**
     * 查询模具类别API
     *
     * @return
     */
    @ApiOperation(value = "查询模具类别API")
    @PostMapping(value = {"/api/vi/mold/type"})
    public ApiResult<List<TreeNode>> getModListForPad() {
        ApiResult<List<TreeNode>> apiResult = new ApiResult<>();
        // 获取模具类别列表
        List<ModuleTypeEntity> moldTypeList = moldTypeService.queryList(null);
        // 找出父类别节点
        List<TreeNode> treeNodes = moldTypeList.stream().filter(moldType -> StrUtil.isEmpty(moldType.getSuperType()) || "0".equals(moldType.getSuperType())).map(moldType ->
                new TreeNode(moldType.getTypeName(), moldType.getId())
        ).collect(Collectors.toList());
        treeNodes.forEach(treeNode -> {
            // 每个模具类别的第一个子元素都是它自身
            TreeNode cloneTreeNode = new TreeNode();
            BeanUtil.copyProperties(treeNode, cloneTreeNode);
            treeNode.getChildren().add(cloneTreeNode);
            // 找出当前模具类别下的子类别
            List<ModuleTypeEntity> matchedMoldTypeList = moldTypeList.stream().filter(moldType -> treeNode.getValue().equals(moldType.getSuperType())).collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(matchedMoldTypeList)) {
                List<TreeNode> matchedTreeNodeList = matchedMoldTypeList.stream().map(moldType ->
                        new TreeNode(moldType.getTypeName(), moldType.getId())
                ).collect(Collectors.toList());
                treeNode.getChildren().addAll(matchedTreeNodeList);
                // 移除这些子元素
                moldTypeList.removeAll(matchedMoldTypeList);
            }
        });
        return apiResult.success(treeNodes);
    }

    @ApiOperation(value = "查询模具位置类别API")
    @GetMapping("/api/vi/mold/positionTypes")
    public ApiResult<List<String>> getSparePartUnitList() {
        ApiResult<List<String>> apiResult = new ApiResult<>();
        String moldTypeConfig = configService.getValue("MOLD_POSITION_TYPE", "");
        return apiResult.success(StrUtil.split(moldTypeConfig, ","));
    }

    /**
     * 模具详情查询API
     *
     * @param loginUser 当前登录用户
     * @param moldId    模具ID
     * @return
     */
    @AuthCheck
    @ApiOperation(value = "模具详情查询API")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "moldId", value = "id", paramType = "path", dataType = "String", required = true)
    })
    @RequestMapping(value = "/api/vi/molds/{moldId}", method = RequestMethod.POST)
    public ApiResult<ModuleArchivesEntity> getModInfo(@ApiIgnore @LoginUser SysUserEntity loginUser, @PathVariable("moldId") String moldId) {
        ApiResult<ModuleArchivesEntity> apiResult = new ApiResult<>();
        ModuleArchivesEntity moduleData = moduleArchivesService.queryObject(moldId);
        return apiResult.success(moduleData);
    }

    /**
     * 模具换件记录查询API
     *
     * @param loginUser 当前登录用户
     * @param params    查询参数
     * @return
     */
    @AuthCheck
    @ApiOperation(value = "模具换件记录查询API")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "typeMethod", value = "换件类型1维修换件 2异常换件", allowableValues = "1,2", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "replaceCode", value = "模具维修或维护工单编码", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "page", value = "当前页码", paramType = "query", dataType = "int", required = true),
            @ApiImplicitParam(name = "limit", value = "每页记录数", paramType = "query", dataType = "int", required = true)
    })
    @RequestMapping(value = "/api/vi/molds/moldReplacePartRecord", method = RequestMethod.POST)
    public ApiResult<PageUtils> loadMoldReplacePart(@ApiIgnore @LoginUser SysUserEntity loginUser, @ApiIgnore @RequestParam Map<String, Object> params) {
        ApiResult<PageUtils> apiResult = new ApiResult<>();
        return apiResult.success(moldReplacePartManager.queryList(params));
    }

    /**
     * 模具维修记录查询API
     *
     * @param loginUser 当前登录用户
     * @param params    查询参数
     * @return
     */
    @AuthCheck
    @ApiOperation(value = "模具维修记录查询API")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "moduleCode", value = "模具编码", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "page", value = "当前页码", paramType = "query", dataType = "int", required = true),
            @ApiImplicitParam(name = "limit", value = "每页记录数", paramType = "query", dataType = "int", required = true)
    })
    @RequestMapping(value = "/api/vi/molds/moldRepairRecord", method = RequestMethod.POST)
    public ApiResult<PageUtils> loadMoldRepairRecord(@ApiIgnore @LoginUser SysUserEntity loginUser, @ApiIgnore @RequestParam Map<String, Object> params) {
        ApiResult<PageUtils> apiResult = new ApiResult<>();
        return apiResult.success(moldRepairRecordManager.queryList(params));
    }

    @AuthCheck
    @ApiOperation(value = "获取模具关联位置API")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "moduleCode", value = "模具编码", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "page", value = "当前页码", paramType = "query", dataType = "int", required = true),
            @ApiImplicitParam(name = "limit", value = "每页记录数", paramType = "query", dataType = "int", required = true)
    })
    @RequestMapping(value = "/api/vi/molds/moldPositionList", method = RequestMethod.POST)
    public ApiResult<PageUtils> loadMoldPositionList(@ApiIgnore @RequestParam Map<String, Object> params) {
        ApiResult<PageUtils> apiResult = new ApiResult<>();
        List<ModulPositionCorrelationEntity> moduleRepairRocordList = modulPositionCorrelationService.queryList(params);
        int total = modulPositionCorrelationService.queryTotal(params);
        return apiResult.success(new PageUtils(moduleRepairRocordList, total, MapUtil.getInt(params, "limit"), MapUtil.getInt(params, "page")));
    }

}
